<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <!-- 引入组件库 -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <div id="app">

    <img src="./1.png" alt="" ref="imageCon" width="100" height="100">
    <button @click="handleAddWaterMarker">添加水印</button>
    <img :src="image" alt="" crossOrigin="Anonymous">




  </div>
  <script>

    var app = new Vue({
      el: '#app',
      data: {
        image: "",
      },
      created () {

      },
      mounted () {

      },
      methods: {

        handleAddWaterMarker () {
          let content = "我就是一个水印";
          let height = 80; //两个水印之间的垂直高度
          let width = 70; //两个水印之间的水平高度
          let fontSize = 14; //水印字体大小
          let imageCon = this.$refs.imageCon;//获取图片
          let canvas = document.createElement("canvas");//创建canvas容器
          canvas.width = imageCon.width;//设置canvas容器宽度
          canvas.height = imageCon.height;//设置canvas容器高度

          let ctx = canvas.getContext("2d");//获取2d画笔

          //在canvas画布上绘制图片 ctx.drawImage(图片, x位置, y位置,  图像宽度, 图像高度);
          ctx.drawImage(imageCon, 0, 0, imageCon.width, imageCon.height);

          //设置文本画笔样式
          ctx.textAlign = 'left';//设置文本对齐方式
          ctx.textBaseline = 'top';//设置文本基线
          ctx.font = `${fontSize}px Microsoft Yahei`;//设置文本字体属性
          ctx.fillStyle = "rgba(255, 255, 255,0.25)"//设置文本字体颜色

          //在canvas画布上绘制文字 ctx.fillText(文字内容, x位置, y位置, 文本最大宽度)
          ctx.rotate(17 * Math.PI / 180)//文本旋转角度设置
          let i = 0, j = 0, waterMarkerWidth = content.split("").length * fontSize;
          for (i = 0; i < imageCon.width / (waterMarkerWidth); i++) {
            for (j = 0; j < imageCon.height / (height - 20); j++) {
              if (j == 0) {
                ctx.fillText(content, i * (waterMarkerWidth + width), -height, imageCon.width)
              }
              ctx.fillText(content, i * (waterMarkerWidth + width), j * height, imageCon.width)
            }
          }

          var image = new Image();
          imageCon.setAttribute('crossOrigin', 'anonymous');//跨域
          imageCon.setAttribute('useCORS', true);//跨域
          image.setAttribute('crossOrigin', 'anonymous');//跨域
          image.setAttribute('useCORS', true);//跨域
          image.src = canvas.toDataURL("image/png");
          console.log('image.src : ', image.src );
          // this.image = image.src

        }

      }
    })
  </script>
</body>

</html>